<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 用户答题记录表（竞答（轮次记录）形式答题）
 */

class AnswerActivityUserCorrectAnswerRecord extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_correct_answer_record';

    
    /**
     * 判断此活动是否有人答过题
     */
    public function  isBeenAnswer($id){
        return $this->where('act_id', $id)->first();
    }

     /**
     * 判断是否有人答过此题
     */
    public function  isBeenProblem($id){
        return $this->where('problem_id', $id)->first();
    }


     /**
     * 写入单位答题记录
     */
    public function addUserCorrectRecord($data,$unit_id,$user_guid , $answer_time , $correct_number_id){
        $arr = [];
        $return_arr = [];
        foreach($data as $key=>$val){
            $level = $key + 1;
            $arr[$key]['correct_number_id'] = $correct_number_id;
            $arr[$key]['user_guid'] = $user_guid;
            $arr[$key]['guid'] = get_guid();
            $arr[$key]['act_id'] = $val['act_id'];
            $arr[$key]['unit_id'] = $unit_id ?: 0;
            $arr[$key]['problem_id'] = $val['id'];
            $arr[$key]['status'] = 0;
            $arr[$key]['level'] = $level;
            $arr[$key]['create_time'] = date('Y-m-d H:i:s');
            $arr[$key]['expire_time'] = date('Y-m-d H:i:s' , strtotime("+".$answer_time*$level." second"));

            $return_arr[$key]['id'] = $val['id'];
            $return_arr[$key]['title'] = $val['title'];
            $return_arr[$key]['img'] = $val['img'];
            $return_arr[$key]['type'] = $val['type'];
            $return_arr[$key]['create_time'] = $val['create_time'];
            $return_arr[$key]['con_answer'] = $val['con_answer'];
            $return_arr[$key]['guid'] = $arr[$key]['guid'];
        }
        $this->insert($arr);
        return $return_arr;
    }

    /**
     * 修改答题记录
     * @param  $status 状态数组 
     */
    public function changeUserCorrectRecord($status){
        foreach($status as $key=>$val){
            $this->where('guid', $key)->update(['answer_id'=>$val['answer_id'],'answer'=>$val['content'],'status'=>$val['status'],'change_time'=>date('Y-m-d H:i:s')]);
        }
    }

     /**
     * 根据guid，获取问题记录
     * @param guid
     */
    public function getCorrectRecordByGuid($guid){
        $res = $this->where('guid', $guid)->first();
        return $res;
    }

    /**
     * 根据 correct_number_id，获取此轮所有问题记录
     * @param $correct_number_id
     */
    public function getCorrectRecordByCorrectNumberId($correct_number_id){
        $res = $this->where('correct_number_id', $correct_number_id)->get();
        return $res;
    }


   /**
     * 获取用户回答的所有题
     * @param act_id 活动id
     * @param user_guid 用户guid
     * @param unit_id 单位id
     * @param status array 答题状态  0表示所有 1代表正确  2代表错误   3 超时回答（算错误）默认2
     */
    public function getHaveAnswer($act_id , $user_guid , $unit_id =null , $status = []){
        $res = $this->where('act_id' , $act_id)
        ->where('user_guid' , $user_guid)
        ->where(function($query) use($unit_id , $status){
                if($unit_id){
                    $query->where('unit_id', $unit_id);
                }
                if($status){
                    $query->whereIn('status', $status);
                }
        })->groupBy('problem_id')
        ->pluck('problem_id')
        ->toArray();
        return $res;
    }
    
    /**
     * 用户参与人次、答题次数统计
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     * @param type 类型 1 参与人次  2 答题次数
     */
    public function partNumberStatistics($act_id, $unit_id = null, $start_time = null, $end_time = null, $type = 1)
    {
        $res = $this->select('id', 'user_guid', 'act_id')
        ->where(function ($query) use ($act_id,$unit_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        });

        if ($type == 1) {
            $res = $res->groupBy('user_guid');
        }
        $result = $res->get()->toArray();

        return count($result);
    }

    
    /**
     * 答题次数统计(折线图)
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     * @param is_month  是否按月统计
     */
    public function partStatistics($act_id, $unit_id = null, $start_time = null, $end_time = null , $is_month = false)
    {
        if (empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }

        if ($is_month) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m') as dates"), DB::raw("count(id) as count")];
        } elseif (date('Y-m-d' , strtotime($start_time)) == date('Y-m-d' , strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as dates"), DB::raw("count(id) as count")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as dates"), DB::raw("count(id) as count")];
        }
        $res = $this->select($field)->where(function ($query) use ($act_id ,$unit_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })
            ->orderBy('dates')
            ->groupBy('dates')
            ->get()
            ->toArray();

        return $res;
    }
}
